#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <poll.h>

int main(int argc, char *argv[]) {
    unsigned int flags = 0;
    struct pollfd pfds[1] = {0};
    int err = 0;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <device>\n", argv[0]);
        return EXIT_FAILURE;
    }

    int fd = open(argv[1], O_RDWR);
    if (fd < 0) {
        perror("Failed to open device");
        return EXIT_FAILURE;
    }

    flags = fcntl(fd, F_GETFL);
    if (flags < 0) {
        perror("Failed to get file flags");
        err = EXIT_FAILURE;
        goto close;
    }
    flags |= O_NONBLOCK; // Set non-blocking mode
    if (fcntl(fd, F_SETFL, flags) < 0) {
        perror("Failed to set file flags");
        err = EXIT_FAILURE;
        goto close;
    }

    pfds[0].fd = fd;
    pfds[0].events = POLLIN; // Monitor for read availability
    err = poll(pfds, 1, -1);
    if (err < 0) {
        perror("Poll failed");
        err = EXIT_FAILURE;
        goto close;
    }
    fprintf(stdout, "Poll returned %d fds ready\n", err);

    if (!(pfds[0].revents & POLLIN)) {
        fprintf(stderr, "No data available to read\n");
        err = EXIT_FAILURE;
        goto close;
    }
    char buffer[100];
    ssize_t bytes_read = read(fd, buffer, sizeof(buffer));
    if (bytes_read < 0) {
        if (errno == EAGAIN) {
            fprintf(stderr, "No data available for reading (non-blocking mode)\n");
        } else {
            perror("Failed to read from device");
            err = EXIT_FAILURE;
        }
        goto close;
    }

    printf("Read %zd bytes: %.*s\n", bytes_read, (int)bytes_read, buffer);

close:
    close(fd);
    return err;
}